<template>
  <div id="reportInfoInstrument">
    <div class="centreportInfoInstrumenterContent">
      <Splitpanes>
        <Pane size="99">
          <el-dialog v-model="showDialog" :title="title" width="500px" @close="closeDialog">
            <!-- 修改表单 -->
            <el-form ref="reportForm" :model="form" :rules="formRule" label-width="100px" class="form-input-m" :inline-message="true">
              <el-form-item prop="name" label="模版名称" v-show="false">
                <el-input type="text" v-model="form.saveAsName" placeholder="请输模版名称" clearable></el-input>
              </el-form-item>
              <el-form-item prop="name" label="报告名称">
                <el-input type="text" v-model="form.name" placeholder="请输入报告名称" clearable></el-input>
                <span v-show="isShowParentName">({{ form.parentName }})</span>
              </el-form-item>

              <el-form-item prop="code" label="编码" v-if="isShowCode">
                <div class="disabled-input-wrapper">
                  <el-input type="text" v-model="form.code" :readonly="true" clearable></el-input>
                </div>
              </el-form-item>

              <el-form-item prop="commonId" label="所属报告组别">
                <el-select v-model="form.commonId">
                  <el-option v-for="reportType in reportTypeList" :key="reportType.code" :label="reportType.name" :value="reportType.code">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="上传模版" prop="reportTemplate" v-show="isUpload">
                <el-upload ref="fileUploadAgain" :action="''" multiple :limit="1" :show-file-list="false" :on-change="uploadTemplateFileAgain" :auto-upload="false">
                  <el-button type="success" plain size="mini" circle>
                    <el-icon class="el-icon">
                      <Upload />
                    </el-icon>
                  </el-button>
                </el-upload>
              </el-form-item>
            </el-form>
            <div class="dialog-footer" style="display: flex; justify-content: center">
              <el-button type="primary" @click="saveHandler('form')">保存</el-button>
              <el-button @click="closeDialog('form')">取消</el-button>
            </div>
          </el-dialog>
          <Splitpanes>
            <Pane size="70">
              <div class="reportBox">
                <vxe-toolbar perfect>
                  <template #buttons>
                    <div class="smallToolTitle">报告</div>
                    <vxe-input v-model="form.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup="keyupEnter" @clear="getReportList" @search-click="handleSearch(form.searchValue)"></vxe-input>

                    <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="loading" @click="getReportList"></vxe-button>
                    <vxe-button type="text" status="success" icon="vxe-icon-square-plus" content="新建" class="button-blue" @click="handleAdd()">
                    </vxe-button>

                    <el-upload ref="uploadFilemany" :action="''" multiple :limit="10000" :show-file-list="false" :file-list="fileList" :on-change="fileSelectChange" :on-success="uploadSuccess" :on-remove="fileRemove" :auto-upload="false">
                      <vxe-button icon="vxe-icon-sort" class="button-blue">批量上传模板</vxe-button>
                    </el-upload>
                  </template>
                </vxe-toolbar>
                <div class="tablebox">
                  <vxe-table border :data="reportList" ref="reportTable" height="auto" :row-config="{ isCurrent: true, isHover: true, height: 33 }" :row-class-name="getRowClassName" :loading="loading" :tree-config="{}" :column-config="{ resizable: true }" :edit-config="{
                      trigger: 'click',
                      mode: 'cell',
                      showStatus: true
                    }" :expand-config="{ expandAll: true, reserve: true }" :checkbox-config="{ labelField: 'title', checkStrictly: true }" class="mytable-scrollbar reportInfoList" @current-change="reportRowClick" resizable show-overflow keep-source>
                    <vxe-column field="code" width="110" title="编号" align="center"> </vxe-column>

                    <vxe-column field="name" title="报告名称" align="center"> </vxe-column>
                    <vxe-column field="commonId" width="150" title="所属报告组别" align="center">
                      <template #default="{ row }">
                        <el-tag>{{ getIsStaticCodeDesc(row) }}</el-tag>
                      </template>
                    </vxe-column>

                    <vxe-column field="isUse" width="100" align="center" title="是否启用">
                      <template #default="{ row }">
                        <vxe-switch v-model="row.isUse" size="mini" open-label="是" close-label="否" open-value="0" close-value="1" @change="handleSwitchChange(row)">
                        </vxe-switch>
                      </template>
                    </vxe-column>
                    <vxe-column field="editTime" width="110" title="最后修改时间" align="center">
                    </vxe-column>
                    <vxe-column title="操作" align="center" fixed="right">
                      <template #default="{ row }">
                        <vxe-button type="text" status="primary" circle @click="handleEide(row, 1)">
                          <!-- <el-icon>
                                    <DocumentAdd />
                                  </el-icon> -->
                          另存为
                        </vxe-button>
                        <!-- </el-tooltip> -->

                        <!-- <el-tooltip class="item" effect="dark" content="下载" placement="right"> -->
                        <vxe-button type="text" status="warning" circle @click="handleDownload(row)">
                          <!-- <el-icon>
                                  <Download />
                                </el-icon> -->
                          下载
                        </vxe-button>
                        <!-- </el-tooltip> -->
                        <!-- <el-tooltip class="item" effect="dark" content="报表编辑" placement="right"> -->
                        <vxe-button type="text" status="success" circle @click="gotoEditPage(row)">
                          <!-- <el-icon>
                                  <Position />
                                </el-icon> -->
                          报表编辑
                        </vxe-button>
                        <!-- </el-tooltip> -->

                        <!-- <el-tooltip class="item" effect="dark" content="编辑" placement="right"> -->
                        <vxe-button type="text" status="primary" circle @click="handleEide(row, 2)" v-show="isShowbutton(row)">
                          <!-- <el-icon>
                                    <Edit />
                                  </el-icon> -->
                          修改
                        </vxe-button>
                        <!-- </el-tooltip> -->

                        <vxe-button type="text" status="danger" circle @click="deleteReport(row)" v-show="isShowbutton(row)">
                          删除
                        </vxe-button>
                      </template>
                    </vxe-column>
                  </vxe-table>
                  <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                      'PrevJump',
                      'PrevPage',
                      'Number',
                      'NextPage',
                      'NextJump',
                      'Sizes',
                      'FullJump',
                      'Total'
                    ]" @page-change="handleSizeChange($event)"></vxe-pager>
                </div>
              </div>
            </Pane>
            <Pane size="30">
              <ReportAttribute ref="refReport" />
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 公共组件标题
const content = ref('报告设置');
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { pageSizes, notifyType, notifyMessage } from '@/utils/common';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeTablePropTypes } from 'vxe-table';
import { ElMessage } from 'element-plus';
import 'splitpanes/dist/splitpanes.css';
import { VXETable } from 'vxe-table';
import XEUtils from 'xe-utils';
import { log } from 'console';
import { VxeMessage } from '@/utils/CommonMessage';
import { AppStore } from '@/stores/store';
import axios from 'axios';
import ReportAttribute from '@/views/system_set/ReportAttribute.vue'; //属性设置
import { Document, Menu as IconMenu, Location, Setting } from '@element-plus/icons-vue';

let store = AppStore();
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
let defaultProps = {
  children: 'children',
  label: 'title'
};
let treeloading = ref(false);

// 页面加载时更新用户列表
let loading = ref(false);
// 弹框表单状态
let showDialog = ref(false);
let isShowCode = ref(false);
let currentKey = ref(''); //树形表格默认选中节点
const size = ref('');

let { proxy }: any = getCurrentInstance();
let form = reactive({
  id: null,
  searchValue: '',
  code: '',
  searchValueMoulde: '',
  name: '',

  reportTemplate: '',
  saveAsName: '',
  isUse: '',
  type: '1',
  parentName: '',
  parentId: '',
  commonId: '10'
});

let reportList: any = reactive([]); //报告列表

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
let moduleList: any = reactive([]); //模块下拉列表
let menuList: any = reactive([]); //菜单下拉
let type = '2'; //报告类别
let refReport: any = ref(null);

let selectfilecount = 0;
let fileList: any = reactive([]); //上传的文件列表
//上传文件状态改变
function fileSelectChange(file) {
  if (commonId === '' || commonId === null) {
    VxeMessage('请选择相应报告组别', 'error');
    return;
  }
  selectfilecount++;
  let name = '';
  let reportTemplate = '';
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e: any) => {
    reportTemplate = e.target.result
      .toString()
      .replace('data:application/octet-stream;base64,', '');
    name = file.name;
    let $el = proxy.$refs.uploadFilemany;
    $el.clearFiles();

    const data = {
      commonId: commonId,
      reportTemplate: reportTemplate,
      name: name,
      reportName: '报告模版',
      type: type
    };
    const url = '/api/pubReport/saveBatch';
    proxy.$http
      .post(url, data)
      .then((res) => {
        selectfilecount--;
        if (selectfilecount <= 0) {
          getReportList();
          ElMessage({
            message: '创建成功',
            type: 'success'
          });
        }
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          message: '创建异常',
          type: 'error'
        });
      });
  };
}

function uploadSuccess(response, file, fileList) {
  selectfilecount--;
  if (selectfilecount <= 0) {
    //刷新列表
  }
}

// 删除上传文件
function fileRemove(file, fileList) {
  //this.workListFileForm.filePath = '';
}

//点击当前行时；把父组件中的当前行数据传给子组件  <ReportAttribute ref="refReport"/>
function reportRowClick({ row }: any) {
  refReport.value.initPage(row);
}

getModuleList();

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(form.searchValue);
  }
}

// 查询/刷新
function handleSearch(row: any) {
  loading.value = true;
  reportList.length = 0;
  const url = '/api/pubReport/getReportList';
  proxy.$http
    .get(url, {
      params: { pageIndex: page.currentPage, pageSize: page.pageSize, keywords: row, type: type, commonId: '10' }
    })
    .then((res: any) => {
      reportList.push(...res.data.reportList.records);
      page.totalResult = res.data.reportList.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询刷新失败', 'error');
    });
}

//下载
function handleDownload(row) {
  // 以之前的post请求举例
  axios
    .get((window as any).apiUrl.VUE_APP_PRINT_URL + '/download-report-file/' + row.name, {
      responseType: 'blob'
    })
    .then((res: any) => {
      console.log(res);
      const fileName = row.name;
      //const blob = new Blob([JSON.stringify(data)], ...)
      const blob = new Blob([res.data], {});
      let dom = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      dom.href = url;
      dom.download = decodeURI(fileName);
      dom.style.display = 'none';
      document.body.appendChild(dom);
      dom.click();
      dom.parentNode.removeChild(dom);
      window.URL.revokeObjectURL(url);
    })
    .catch((err) => {
      console.log('异常', err);
    });
}
//根据词典列表获取组名称
function getIsStaticCodeDesc(row: any) {
  const obj = reportTypeList.find((reportType) => reportType.code === row.commonId);
  if (obj !== null && obj !== undefined) {
    return obj.name;
  } else {
    return '';
  }
}
//预览
function gotoEditPage(row) {
  if (row) {
    window.open((window as any).apiUrl.VUE_APP_PRINT_URL + '/designer/edit/' + row.name, '_blank');
    return;
  }
  window.open((window as any).apiUrl.VUE_APP_PRINT_URL + '/designer', '_blank');
}

//更改开关状态
function handleSwitchChange(row) {
  // reportList.forEach((item) => {
  //       if (item !== row) {
  //         item.isUse = "1";
  //       }
  //     });
  const data = {
    id: row.id,
    name: row.name,
    isUse: row.isUse,
    commonId: row.commonId,
    type: type
  };
  const url = 'api/pubReport/updateUse';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        // getReportList();
        ElMessage({
          message: res.status.msg,
          type: 'success'
        });
      } else {
        VxeMessage(res.status.msg, 'error');
      }
    })
    .catch((err: any) => {
      VxeMessage('失败', 'error');
    });
}

onMounted(() => {
  getReportTypeList();
  getReportList()
});

let reportTypeList: any = reactive([]);
//从词典获取所有的报告组
// 获取界面字段
function getReportTypeList() {
  reportTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'JYGZZ'} })
    .then((res: any) => {
      reportTypeList.push(...res.data);
      currentKey.value = reportTypeList[0].commonId;

      proxy.$nextTick(() => {
        proxy.$refs.dataTreeRef.setCurrentKey(currentKey.value);
        handleClickType(reportTypeList[0]);
      });

      // console.log('reportTypeList---------------',reportTypeList);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//获取所有模块
function getModuleList() {
  // moduleList.length = 0;
  // proxy.$http
  //   .get('/api/sys/getModuleList', { params: { keywords: '' } })
  //   .then((res) => {
  //     console.log('moduleList数据列表', res.data.moduleList);
  //     moduleList.push(...res.data.moduleList);
  //   });
}

const filteredMenuList = ref([]);

function openCheckBox(row) {
  return true;
}
let commonId = '10';
function handleClickType(selectValue: any) {
  // commonId = selectValue.code;
  commonId ='10';
  getReportList();
}

function deleteReport(row) {
  const data = {
    id: row.id,
    name: row.name
  };
  const url = 'api/pubReport/deleteReport';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        getReportList();
        ElMessage({
          message: res.status.msg,
          type: 'success'
        });
      } else {
        VxeMessage(res.status.msg, 'error');
      }
    })
    .catch((err: any) => {
      VxeMessage('失败', 'error');
    });
}

function isShowSaveAs(row) {
  let userInfo = store.userInfo;
  if (row.parentId === null || row.parentId === '' || row.parentId === undefined) {
    return true;
  } else {
    return false;
  }
}

function isShowbutton(row) {
  let userInfo = store.userInfo;

  if (userInfo.realname === '管理员') {
    return true;
  }

  if (row.parentId !== null && row.parentId !== '' && row.parentId !== undefined) {
    return true;
  }
}

//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getReportList();
}

// 用户输入关键字
let keywordsMoudle = ref('');
// getReportList();
//getModuleAndPointList()

// 获取报告信息
function getReportList() {
  loading.value = true;
  reportList.length = 0; //放入数据前清空数
  const data = {
    params: {
      pageIndex: page.currentPage,
      pageSize: page.pageSize,
      commonId: commonId,
      type: '2',
      keywords: keywordsMoudle.value
    }
  };
  const url = 'api/pubReport/getReportList';
  proxy.$http
    .get(url, data)
    .then((res: any) => {
      reportList.push(...res.data.reportList.records);
      page.totalResult = res.data.reportList.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索报告列表失败', 'error');
    });
}

//moduleAndPointList 获取业务表单中的树形菜单----模块---功能

function getModuleAndPointList() { }

let title = ref('');
let isUpload = ref(true);
let addType = ref('');
let isShowParentName = ref(false);
function handleEide(row, type) {
  //let rowName = row.name;
  addType.value = type;
  if (type === 1) {
    //另存为模版
    title.value = '另存为模版';
    //隐藏上传按钮
    isUpload.value = false;
    isShowCode.value = false;
    form.name = '';
    if (row.parentName === null || row.parentName === '' || row.parentName === undefined) {
      form.parentName = row.name;
    } else {
      form.parentName = row.parentName;
    }
    isShowParentName.value = true;
    const url = '/api/pub/getReportAsName';
    proxy.$http
      .post(url)
      .then((res) => {
        form.name = '(自定义)' + res.data;
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          message: '获取另存为名称异常',
          type: 'error'
        });
      });
  } else if (type === 2) {
    title.value = '修改模版';
    form.name = row.name;
    isShowCode.value = true;
    if (row.parentName !== null && row.parentName !== '' && row.parentName !== undefined) {
      form.parentName = row.parentName;
      isShowParentName.value = true;
    }
  }
  showDialog.value = true;

  form.code = row.code;

  form.reportTemplate = row.reportTemplate;
  form.saveAsName = row.name;
  form.parentId = row.parentId;
  form.commonId = row.commonId;
  form.id = row.id;
  form.type = '2';
  // filteredMenuList.value = menuList.filter(menu => menu.moduleId === row.moduleId);
}

const fileUploadAgain = ref();
//重新上传文件状态改变
function uploadTemplateFileAgain(file) {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e: any) => {
    form.reportTemplate = e.target.result
      .toString()
      .replace('data:application/octet-stream;base64,', '');
    form.name = file.name;
    let $el = proxy.$refs.fileUploadAgain;

    $el.clearFiles();
  };
}

function clearFormAndobj() {
  (form.id = null),
    (form.searchValue = ''),
    (form.code = ''),
    (form.searchValueMoulde = ''),
    (form.name = ''),
    (form.parentName = '');
  (form.parentId = ''), (form.commonId = '10'), (form.type = '2');
  showDialog.value = false;
  //放开上传按钮
  isUpload.value = true;
  addType.value = '';
  isShowCode.value = false;
  isShowParentName.value = false;
}

// 弹框取消
function closeDialog() {
  let $form = proxy.$refs.reportForm;
  $form.resetFields();
  clearFormAndobj();
}

// 点击新增
function handleAdd() {
  clearFormAndobj();
  showDialog.value = true;
  addType.value = '0'; //新增
  title.value = '新建报告模版';
}

// 表格规则
let formRule = ref({
  // code: [
  //   {
  //     required: true,
  //     message: '请输入编码',
  //     trigger: 'blur'
  //   },
  //   {
  //     min: 2,
  //     max: 20,
  //     message: '长度为2到32个字符',
  //     trigger: 'blur'
  //   }
  // ],
  name: [
    {
      required: true,
      message: '请输入报告名称',
      trigger: 'blur'
    }
  ]
});

// 弹框保存
function saveHandler() {
  let $form = proxy.$refs.reportForm;
  $form.validate((valid: any) => {
    // 表单校验
    //
    if (!valid) {
      return false;
    } else {
      if (form.id == '' || form.id == null || form.id == undefined) {
        const url = '/api/pubReport/addReportBusiness';
        let PubReport = form;
        proxy.$http
          .post(url, PubReport)
          .then((res) => {
            getReportList();
            clearFormAndobj();
            $form.resetFields();

            ElMessage({
              message: '创建成功',
              type: 'success'
            });
          })
          .catch((err) => {
            console.log(err);
            ElMessage({
              message: '创建异常',
              type: 'error'
            });
          });
      } else {
        // 两种情况  addType 1 另存为  2 修改
        if (addType.value === 1) {
          const url = '/api/pubReport/saveAsReportBusiness';
          let PubReport = form;
          proxy.$http
            .post(url, PubReport)
            .then((res) => {
              clearFormAndobj();
              getReportList();
              ElMessage({
                message: '另存为成功',
                type: 'success'
              });
            })
            .catch((err) => {
              console.log(err);
              ElMessage({
                message: '创建异常',
                type: 'error'
              });
            });
        } else if (addType.value === 2) {
          //修改模版
          const url = '/api/pubReport/updateReportBusiness';
          let PubReport = form;
          proxy.$http
            .post(url, PubReport)
            .then((res) => {
              if (res.status.code === 200) {
                clearFormAndobj();
                getReportList();
                ElMessage({
                  message: res.status.msg,
                  type: 'success'
                });
              } else {
                VxeMessage(res.status.msg, 'error');
              }
            })
            .catch((err) => {
              console.log(err);
              ElMessage({
                message: '修改异常',
                type: 'error'
              });
            });
        }
      }
    }
  });
}

function getRowClassName({ row }) {
  if (row.parentId !== null && row.parentId !== '' && row.parentId !== undefined) {
    return 'row-green';
  }
  return null;
}
</script>

<style lang="scss" scoped>
#reportInfoInstrument {
  width: 100%;
  height: 100%;

  .centreportInfoInstrumenterContent {
    height: 100%;

    .sampleType {
      .tools-tree {
        min-width: 168px;
        padding: 0 5px 5px 5px;
        font-size: $font-size;
        border: none;
      }
    }

    .reportBox {
      height: 100%;

      .tablebox {
        height: calc(100% - 40px);

        :deep(.vxe-table--render-default) {
          height: calc(100% - 32px);
        }

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }

  :deep(.reportInfoList.vxe-table .vxe-body--row.row-green) {
    background-color: rgb(255, 255, 225); // color: #fff;
  }
}
</style>
